package com.longge;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

public class ShortestCompletingWord {
    public String shortestCompletingWord(String licensePlate, String[] words) {
        Map<Character, Integer> mapCount = new HashMap<>();
        String str = licensePlate.toLowerCase();
        int count = 0;
        for (int i = 0; i < licensePlate.length(); i++) {
            char key = str.charAt(i);
            if (Character.isLetter(key)) {
                Integer num = mapCount.getOrDefault(key, 0);
                mapCount.put(key, num + 1);
                count++;
            }
        }

        int min = Integer.MAX_VALUE;
        String res = "";

        for (String word : words) {
            Map<Character, Integer> newMapCount = new HashMap<>(mapCount);
            int sum = 0;
            for (int i = 0; i < word.length(); i++) {
                Integer num = newMapCount.get(word.charAt(i));
                if (Objects.isNull(num) || num <= 0) continue;
                newMapCount.put(word.charAt(i), num - 1);
            }
            for (Integer value : newMapCount.values()) {
                sum += value;
            }
            if (sum == 0) {
                if (min > word.length()) {
                    min = word.length();
                    res = word;
                }
            }
        }
        return res;


    }
}
